import { designW, divisor, precision } from "../config/app";

export const pxChangeRem = (px: number | string) => {
  px = parseFloat(px as string);
  const value =
    Math.round((px / (designW / divisor)) * divisor ** precision) /
    10 ** precision;
  return value + "rem";
};

export const getImg = (str: string | undefined) => {
  if (!str) {
    return "";
  }
  return new URL(`../assets/img/${str}`, import.meta.url).href;
};
export const getGamesImg = (dir: string | undefined, name: string) => {
  if (!dir) return "";
  return `./games_img/${dir}/${name}.png`
};
export const getSvg = (str: string | undefined) => {
  if (!str) {
    return "";
  }
  return new URL(`../assets/svg/${str}.svg`, import.meta.url).href;
};
export const getIcon = (str: string | undefined) => {
  if (!str) {
    return "";
  }
  return new URL(`../assets/icons/${str}`, import.meta.url).href;
};

// export function getParam(key: string): string | null {
//   const searchParams = new URLSearchParams(window.location.search);
//   const searchValue = searchParams.get(key);
//   if (searchValue !== null) {
//     return searchValue;
//   }
//   const hash = window.location.hash;
//   const hashSearchMatch = hash.match(/(?<=#.*\?).*/);
//   if (hashSearchMatch) {
//     const hashSearchParams = new URLSearchParams(hashSearchMatch[0]);
//     return hashSearchParams.get(key);
//   }
//   return null;
// }

export const trimParams = (object: any) => {
  if (isEmptyType(object)) return object;
  const tmpObject: any = {};
  Object.keys(object).forEach((key) => {
    if (!isEmptyType(object[key])) {
      tmpObject[key] = object[key];
    }
  });
  return tmpObject;
};

export const chunkArray = (array: any[], size: number = 2) => {
  let result = [];
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }
  return result;
};

// 从一个数组当中随机选取 n 个元素
export const getRandomItems = (arr: any[], count: number) => {
  if (arr.length <= count) {
    return arr;
  }
  const shuffled = arr.sort(() => 0.5 - Math.random());
  return shuffled.slice(0, count);
};

/**
 * 加载外链js
 * @param url
 * @param callback
 */

export function loadScript(url: string, callback: () => void) {
  try {
    let script: any = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    script.setAttribute("crossorigin", "anonymous");

    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else {
      script.onload = function () {
        callback();
      };
      script.onerror = (event: any) => {
        console.log(event);
      };
    }
    script.src = url;
    document.head.appendChild(script);
  } catch (e) {
    console.error("Error loading script:", e);
  }
}